using ED.Common;
using ED.Common.BaseModel;
using ED.Common.Extensions;
using ED.Common.Utils;
using ED.Entity;
using ED.IRepository;
using ED.IService;
using ED.Model.Request;
using static ED.Model.Request.DepartmentOperateReq;

/// <summary>
/// Department服务
/// </summary>
namespace ED.Service
{
    public class DepartmentService : IDepartmentService
    {
        private readonly IDepartmentRepository departmentRepository;
        public DepartmentService(IDepartmentRepository departmentRepository)
        {
            this.departmentRepository = departmentRepository;
        }

        /// <summary>
        /// Department添加
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public ResponseOutput Add(DepartmentOperateReq req)
        {
            ModelValidatorHelp<DepartmentOperateReq>.Valid(new DepartmentValidator(), req);
            if (departmentRepository.Get(t => t.Name == req.Name).Id > 0)
            {
                return ResponseOutput.NotOk("机构名称重复");
            }
            var entity = req.MapTo<Base_DepartmentEntity>();
            departmentRepository.Insert(entity);
            return ResponseOutput.Ok("添加成功");
        }

        /// <summary>
        /// Department删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ResponseOutput Delete(int Id)
        {
            departmentRepository.Delete(Id);
            return ResponseOutput.Ok("删除成功");
        }

        /// <summary>
        /// Department查询 树形结构
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public List<DepartmentRes> Page(DepartmentQueryReq req)
        {
            var resList = departmentRepository.GetList().Mapper<List<DepartmentRes>>().FetchToTree(t => t.Id, t => t.ParentId, t => t.Children, t => t.ParentId == 0);
            return resList;

        }

        /// <summary>
        /// Department更新
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public ResponseOutput Update(DepartmentOperateReq req)
        {
            if (req.Id.IsDefault())
            {
                ThrowHelp.Throw("部门编号不允许为空");
            }

            ModelValidatorHelp<DepartmentOperateReq>.Valid(new DepartmentValidator(), req);
            if (departmentRepository.Get(t => t.Name == req.Name && t.Id != req.Id).Id > 0)
            {
                return ResponseOutput.NotOk("机构名称重复");
            }

            var entity = req.MapTo<Base_DepartmentEntity>();
            departmentRepository.Insert(entity);
            return ResponseOutput.Ok("更新成功");
        }
    }
}
